import {
  debounce,
  throttle
} from '../../../utils/vutils.js'

const app = getApp();
const BALL_LEN = 10
let openCartBoxNum = 0 // 打开购物车盒子的数量

// 创建小球数组
function createBalls() {
  let balls = []
  for (let i = 0; i < BALL_LEN; i++) {
    balls.push({
      index: i,
      show: false,
      fixedX: 0,
      fixedY: 0,
      animationX: {},
      animationY: {}
    })
  }
  return balls
}

Component({

  options: {
    multipleSlots: true // 开启插槽
  },

  /**
   * 组件的属性列表
   */
  properties: {
    cartList: {
      type: Array,
      observer: function (newVal, oldVal, changedPath) {
        if (newVal.length === 0) {
          this.setData({
            isShowCartList: false
          })
        }
      }
    }, // 购物车列表
    cartRecommendGoods: Array, // 购物车匹配商品
    discountsInfo: Object, // 优惠信息
    storeInfo: Object, // 店铺信息 
    isStoreOpen: {
      type: Boolean,
      value: true
    }, // 店铺是否打烊
    isShowCartAlert: {
      type: Boolean,
      value: false
    }, // 是否显示购物车提示
  },

  /**
   * 组件的初始数据
   */
  data: {
    balls: createBalls(),
    dropBalls: [],
    cartImgX: 0,
    cartImgY: 0,
    isShowCartList: false, // 是否显示购物车列表
    isShowRecommendGoodsDialog: false, // 是否显示推荐商品弹出框
    isOpenCartBox: false // 是否打开购物栏盒子
  },

  pageLifetimes: {
    show: function() {
      // 页面被展示
      // 订阅加入购物车动画
      app.event.on('addCartAnimation', this.onAddCartAnimation, this);
    }
  },

  lifetimes: {
    ready: function() {
      app.event.on('addCartAnimation', this.onAddCartAnimation, this);
      this.getRect('.cart-num-img').then(res => {
        console.log('ready res', res)
        this.setData({
          cartImgX: res.left + parseInt(res.width / 2) - 16,
          cartImgY: res.top + 40
        })
      })
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
      // 移除加入购物车动画订阅
      app.event.off('addCartAnimation', this.onAddCartAnimation)
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 显示购物车列表
    onShowCartList() {
      const {
        cartList,
        isStoreOpen
      } = this.properties
      if (cartList.length !== 0 && isStoreOpen) {
        this.setData({
          isShowCartList: !this.data.isShowCartList
        })
      }
    },
    // 关闭购物车列表
    onCloseCartList() {
      this.setData({
        isShowCartList: false
      })
    },
    // 显示推荐商品对话框
    onShowGoodsDialog() {
      const {
        cartRecommendGoods
      } = this.properties
      if (cartRecommendGoods && cartRecommendGoods.length !== 0) {
        this.setData({
          isShowRecommendGoodsDialog: true
        })
      }
    },
    // 提示取消按钮
    onAlertCancel() {
      this.triggerEvent("alertCancel")
    },
    // 提示确认按钮
    onAlertConfirm() {
      this.triggerEvent("alertConfirm")
    },
    // 结算按钮
    onClearing() {
      this.triggerEvent("clearing")
    },
    // 清空购物车
    onClearCart() {
      this.triggerEvent("clearCartList")
    },
    // 修改购物车数量
    onChangeStepper: debounce(function (event) {
      const {
        skuid,
        spuid,
        currentnum,
        goodsimg,
        goodsname
      } = event.currentTarget.dataset
      let goods = {
        goodsThumbnailUrl: goodsimg,
        goodsTitle: goodsname,
        skuId: skuid,
        spuId: spuid,
        skuAmount: event.detail
      }
      this.triggerEvent("changeStepper", {
        goods: goods
      })
    }, 200),
    // 加入购物车动画回调
    onAddCartAnimation(pos) {
      for (let i = 0; i < this.data.balls.length; i++) {
        let ball = this.data.balls[i]
        let dropBallsArr = this.data.dropBalls
        if (!ball.show) {
          ball.show = true
          ball.pos = pos
          ball.index = i
          dropBallsArr.push(ball)
          this.setData({
            dropBalls: dropBallsArr
          })
          this.cartAnimation(i, pos.x, pos.y)
          return
        }
      }
    },
    // 创建动画
    cartAnimation(currentIndex, x, y) {
      console.log(`cartAnimation`)
      const {
        dropBalls
      } = this.data
      let self = this,
        cartY = this.data.cartImgY,
        cartX = this.data.cartImgX
      let dropBallsIndex = dropBalls.findIndex(item => item.index === currentIndex)
      dropBalls[dropBallsIndex].fixedX = x
      dropBalls[dropBallsIndex].fixedY = y
      dropBalls[dropBallsIndex].show = true
      this.setData({
        dropBalls
      })
      this.openCartBox()
      this.setTimeoutPromise(50).then(() => {
        let dropBallListIndex = this.data.dropBalls.findIndex((item) => item.index === currentIndex)
        dropBalls[dropBallListIndex].animationX = this.flyX(cartX, x).export()
        dropBalls[dropBallListIndex].animationY = this.flyY(cartY, y).export()
        self.setData({
          dropBalls
        })
        return this.setTimeoutPromise(500)
      }).then(() => {
        const {
          dropBalls
        } = this.data
        let ball = dropBalls.shift()
        this.setData({
          dropBalls: dropBalls
        })
        this.hidenCartBox()
        if (ball) {
          let ballsIndex = this.data.balls.findIndex((item) => item.index === ball.index)
          const {
            balls
          } = this.data
          balls[ballsIndex].fixedX = 0
          balls[ballsIndex].fixedY = 0
          balls[ballsIndex].animationX = {}
          balls[ballsIndex].animationY = {}
          balls[ballsIndex].show = false
          this.setData({
            balls: balls
          })
        }
      })
    },
    // 创建小球对X轴平移
    flyX(cartX, oriX, duration) {
      let animation = wx.createAnimation({
        duration: duration || 500,
        timingFunction: 'linear',
      })
      animation.translateX(cartX - oriX).step()
      return animation
    },
    // 创建小球对Y轴平移
    flyY(cartY, oriY, duration) {
      let animation = wx.createAnimation({
        duration: duration || 500,
        timingFunction: 'ease-in',
      })
      animation.translateY(cartY - oriY).step()
      return animation
    },
    // 打开购物车盒子
    openCartBox() {
      if (openCartBoxNum === 0) {
        this.setData({
          isOpenCartBox: true
        })
      }
      openCartBoxNum++
    },
    // 关闭购物车盒子
    hidenCartBox() {
      if(openCartBoxNum <= 0) return
      openCartBoxNum--
      if(openCartBoxNum === 0) {
        setTimeout(() => {
          this.closeCartBox()
        }, 300)
      }
    },
    // 关闭购物车盒子
    closeCartBox() {
      if (openCartBoxNum === 0) {
        this.setData({
          isOpenCartBox: false
        })
      }
    },
    // 同步操作，传入定时器时间，
    setTimeoutPromise(sec) { // Promise 化 setTimeout
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, sec)
      })
    },
    // 获取节点信息的对象
    getRect(selector, all) {
      return new Promise(resolve => {
        wx.createSelectorQuery()
          .in(this)[all ? 'selectAll' : 'select'](selector)
          .boundingClientRect(rect => {
            if (all && Array.isArray(rect) && rect.length) {
              resolve(rect);
            }
            if (!all && rect) {
              resolve(rect);
            }
          })
          .exec();
      });
    }
  }
})